package net.cmbt.okframe.okupgrade;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import net.cmbt.okframe.R;
import java.io.File;

/**
 * Created by LG on 2019/12/10.
 */

public class UpdateApp {

    Activity mainActivity;
    private AlertDialog.Builder builder;
    private ProgressBar game_pro;
    private LinearLayout pro_gone;
    private ArrowProgressBar sadsada;
    private TextView app_version;
    private Dialog show_alldialog;
    String file_url;

    public  void updateApp(final Activity mainActivity, final String version, String file_url, String title, String content, boolean isMust) {
        this.mainActivity = mainActivity;

        this.file_url = file_url;
        if (calcVersion(version)) {
            AppleDialog appleDialog = new AppleDialog(mainActivity);
            appleDialog.setCancelable(false);
            appleDialog.editDlalog(title, content, isMust ? "" : "取消更新", "立即更新", new AppleDialog.DialogListener() {
                @Override
                public void sureListener() {
                    builder = new AlertDialog.Builder(mainActivity);
                    View view = View.inflate(mainActivity, R.layout.update_progress, null);
                    game_pro = (ProgressBar) view.findViewById(R.id.game_pro);
                    pro_gone = (LinearLayout) view.findViewById(R.id.pro_gone);
                    sadsada = (ArrowProgressBar) view.findViewById(R.id.sadsada);
                    app_version = (TextView) view.findViewById(R.id.app_version);
                    app_version.setText(getAppName(mainActivity) + " V" + version);
                    builder.setView(view);
                    builder.setCancelable(false);
                    show_alldialog = builder.show();
                    startUpload();
                }

                @Override
                public void cancleListener() {

                }
            });

        } else {
        }

    }


    private void startUpload() {

        DownloadUtil.get().download(file_url, "download", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final File file) {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        show_alldialog.dismiss();
                        Toast.makeText(mainActivity, "下载完成", Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(mainActivity, "net.cmbt.okframe" + ".fileProvider", file);
                            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                        } else {
                            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        }
                        mainActivity.startActivity(intent);
                        mainActivity.finish();
                    }
                });
            }

            @Override
            public void onDownloading(final int progress) {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        pro_gone.setVisibility(View.VISIBLE);
                        game_pro.setProgress(progress);
                        sadsada.setProgress(progress);
                    }
                });
            }

            @Override
            public void onDownloadFailed() {
                mainActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mainActivity, "下载失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

    }


    /**
     * 版本判断 遵循满16进1版本规则 例1.0.16 > 1.1.0
     *
     * @param lineVersion
     */
    private boolean calcVersion(String lineVersion) {
        try {

            String outlineVersion = getAppVersionName(mainActivity);
            String[] lineVersions = lineVersion.split("\\.");
            String[] outlineVersions = outlineVersion.split("\\.");
            if (Integer.parseInt(lineVersions[0]) < Integer.parseInt(outlineVersions[0])) {
                return false;
            } else {
                if (Integer.parseInt(lineVersions[0]) == Integer.parseInt(outlineVersions[0])) {
                    if (Integer.parseInt(lineVersions[1]) < Integer.parseInt(outlineVersions[1])) {
                        return false;
                    } else {
                        if (Integer.parseInt(lineVersions[1]) == Integer.parseInt(outlineVersions[1])) {
                            if (Integer.parseInt(lineVersions[2]) <= Integer.parseInt(outlineVersions[2])) {
                                return false;
                            } else {
                                return true;
                            }
                        } else {
                            return true;
                        }
                    }
                } else {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
//            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }


    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }
}